<template>
  <div class="signleHome">
    <teamName></teamName>
    <!-- 单打报名 -->
    <div class="formItem">
      <van-popup v-model="showAreaSelect" position="bottom"><van-area :area-list="areaList" @confirm="areaChange" @cancel="hideAreaSelect" /></van-popup>
      <van-cell-group>
        <van-cell title="姓名" class="cell">
          <template slot="">
            <van-field class="input" v-model="user.name" maxlength="8" placeholder="请输入姓名" clearable input-align="right" />
          </template>
        </van-cell>
        <van-cell title="年龄" class="cell">
            <van-field class="input" v-model="user.age" type="number" readonly maxlength="4" placeholder="请选择年龄" @click="showpop" clearable input-align="right" />
        </van-cell>
        <van-cell title="性别" class="cell">
          <template slot="">
           <!-- <div class="select-box">
              <div :class="user.sex ? '' : 'activeSex'">
                <i class="iconfont icon-nan "></i>
                <span>男</span>
              </div>
              <div style="margin-left: 0.5rem" :class="user.sex ? 'activeSex' : ''">
                <i class="iconfont icon-nv "></i>
                <span>女</span>
              </div>
            </div> -->
						<van-radio-group v-model="user.sex">
						  <van-radio name="0" checked-color="#42B572" @click="selectSex(0)">男</van-radio>
						  <van-radio name="1" checked-color="#42B572" @click="selectSex(1)">女</van-radio>
						</van-radio-group>
          </template>
        </van-cell>
        <van-cell title="手机号码" class="cell">
          <template slot="">
            <van-field class="short-input" v-model="user.phone" maxlength="11" placeholder="请输入手机号" clearable input-align="right" />
          </template>
        </van-cell>
        <van-cell title="证件号" class="cell">
          <template slot="">
            <van-field class="long-input" v-model="user.id_card" maxlength="18" clearable placeholder="请输入" input-align="right" />
          </template>
        </van-cell>
        <van-cell :title="item.name" class="cell" v-for="(item, index) in customize" :key="index">
          <template slot="">
            <van-field class="long-input" v-model="item.value" maxlength="18" clearable placeholder="请输入" input-align="right" />
          </template>
        </van-cell>
      </van-cell-group>
			
    </div>
    <div class="confirm" style="position: relative;">
			<van-checkbox v-model="read" checked-color="#07c160" @change="readrule" style="position: absolute;left: 0.2rem;top: -0.2rem;">同意<span style="color: #42B574;text-decoration: underline;">《防疫提醒和报名须知》</span></van-checkbox>
      <div class="confirmBtn" :class="{ wechat_bg: sign_up_click }" @click="confirmPay" v-if="!Pay">确认并缴费</div>
      <div v-if="Pay" class="pay-box">
        <div>
          支付：
          <span style="color: red" v-if="is_pay == 1">已支付</span>
          <span style="color: red" v-if="is_pay == 0">未支付</span>
        </div>
        <div class="pay-box-method">
          <!-- 选择支付方式： -->
          <div class="wechat" :class="{ wechat_bg: !is_click }" @click="weixinPay">微信支付</div>
        </div>
      </div>
    </div>
		<van-popup v-model="showrule" round :style="{ height: '60%',width:'80%' }" class="notice">
			<div class="article" style="padding: .5rem;text-align: left;">
				<h3 style="text-align: center;margin: 0.3rem 0;">防疫提醒和报名须知</h3>
				{{rule}}
			</div>
		</van-popup>
		<!-- <van-picker show-toolbar v-show="show" title="请选择年龄" :columns="columns" :default-index="14" @confirm="onConfirm" @cancel="onCancel" @change="onChange"/> -->
		<van-popup  v-model="show" position="bottom" :style="{ height: '30%' }" >
			<van-picker
			  title="请选择年龄"
			  show-toolbar
			  :columns="columns"
			  @confirm="onConfirm"
			  @cancel="onCancel"
			  @change="onChange"
				ref="picker"
			/>
		</van-popup>
	</div>
</template>
<script>
import areaList from 'vant/packages/area/demo/area.js';
import teamName from './formTitle';
// import formItem from './formItem'
import formMultiple from './forMultiple';
// import wx from 'weixin-js-sdk'
import { Toast } from 'vant';
import { mapGetters, mapState } from 'vuex';
import { Picker } from 'vant';
export default {
  name: 'singleHome',
  data() {
    return {
      Pay: false,
      is_pay: null,
      // sign_info: [],
      com: null,
      areaList,
			show:false,
			columns:[15,16,17,18,19,20,21,22],
			load:false,
      showAreaSelect: false,
			noread:true,
			showrule:false,
			read:'',
			rule:'',
      user: {
        name: '',
        age: '24',
        sex: '',
        phone: '',
        id_card: '',
        regist_num: '',
        province: ''
      },
      customize: [],
      is_click: true,
      sign_up_click: true
    };
  },
  computed: {
    ...mapGetters(['GET_SEX'])
  },
  components: {
    teamName
    // formItem
  },
  created() {
		this.rule = '（一）为配合疫情防控要求，本次赛事需遵守地方防疫政策。（二）所有参赛选手须在报名前确定“健康码”须符合比赛地健康码“绿码”且体温正常（37.3℃以下），无相关症状（干咳、乏力、咽痛、腹泻）的要求方可报名参赛。（三）比赛当天参赛选手“健康码”需为绿码且健康状况正常，须科学佩戴口罩（比赛期间可不佩带），赛前检录经测量体温正常（37.3℃以下），方可进入集结区及各功能区。（四）既往新冠肺炎确诊病例、疑似病例、无症状感染者及其密切接触者、确诊病例处于出院后的隔离医学观察期、无症状感染者处于解除隔离治疗或集中隔离医学观察后的医学观察随访期、入境后集中隔离医学观察期、不能提供相关证明材料等情况的人员，不得参加比赛。（五）所有的参赛选手都须遵从赛事组委会的防疫要求，否则将取消参赛资格。（六）如国内疫情出现新的变化，组委会将根据新的疫情防控要求对赛事做进一步调整'
    this.sign_up_info();
    this.userInfo();
		this.setAge()
  },
  methods: {
		// 阅读报名须知
		readrule(){
			this.showrule=true
			this.noread = !this.noread 
		},
		showpop(){
			this.show = true
			setTimeout(()=>{
				this.$refs.picker.setColumnIndex(0,14)
			},100)
		},
		setAge(){
			this.load = true
			// let age = 4+(Math.random()*94-4)
			var arr = []
			for (var i=4;i<=90; i++){
				arr.push(i.toString())
			}
			this.columns = arr
			this.load = false
		},
		onConfirm(value, index) {
			// Toast(`当前值：${value}, 当前索引：${index}`);
			this.show = false
			this.user.age = value
		},
		onChange(picker, value, index) {
			// Toast(`当前值：${value}, 当前索引：${index}`);
			this.user.age = value
			
			// console.log(this.user.age)
		},
		onCancel() {
			// Toast('取消');
			this.show = false
		},
    userInfo() {
      this.$axios
        .get('/mobile/v1/PersonalCenter/my_info', {
          headers: {
            token: window.sessionStorage.getItem('token')
          }
        })
        .then(res => {
					console.log(res)
          if (res.data.code == 2000) {
            this.user = res.data.data.user_info;
						this.user.sex = this.user.sex.toString()
						console.log(this.user.sex)
						this.age = '24'
          }
        })
        .catch(res => {
          //console.log(res.msg);
        });
    },
    confirmPay() {
      if (this.user.name != '' && this.user.age != '' && this.user.age != undefined && this.user.id_card != '' && this.user.phone != '') {
        if (this.sign_up_click) {
          this.sign_up_click = false;
          let customizeValue = [];
          for (let i = 0; i < this.customize.length; i++) {
            if (this.customize[i].value.trim() !== '') {
              customizeValue.push(this.customize[i].value);
            } else {
              Toast('请填写完整信息！');
              return;
            }
          }
					let matchType = this.$route.query.projectType
					console.log(matchType.indexOf('男'))
					if(matchType.indexOf('男')!='-1'&&this.user.sex==1){
						Toast('该比赛仅限男性运动员参加')
						return
					}else if(matchType.indexOf('女')!='-1'&&this.user.sex==0){
						Toast('该比赛仅限女性运动员参加')
						return
					}else{
					}
					if(this.noread){
						Toast('请先同意防疫提醒和报名须知')
						return
					}
          let params = new URLSearchParams();
          params.append('project_id', this.$route.query.project_id);
          params.append('com_id', this.$route.query.com_id);
          params.append('group_type', this.$route.query.projectType);
          params.append('name', this.user.name);
          params.append('age', this.user.age);
          params.append('sex', this.user.sex);
          params.append('phone', this.user.phone);
          params.append('card', this.user.id_card);
          params.append('regist_num', this.user.regist_num);
          params.append('province', this.user.province);
          params.append('customize', customizeValue);
          this.$axios
            .post('/mobile/v1/apply/sign_up', params, {
              headers: {
                token: window.sessionStorage.getItem('token')
              }
            })
            .then(res => {
              if (res.data.code == 200) {
                this.Pay = true;
                this.$toast(res.data.msg);
              }
              if (res.data.code == 400) {
                setTimeout(() => {
                  this.sign_up_click = true;
                }, 3000);
                this.$toast(res.data.msg);
              }
            })
            .catch(res => {
              //  console.log(res.msg);
            });
        } else {
          this.sign_up_click = true;
					this.$axios('请不要重复点击')
        }
      } else {
        this.$toast('请填写完整信息！');
        return;
      }
    },
    sign_up_info() {
      this.$axios
        .get('/mobile/v1/apply/sign_up_info', {
          params: {
            project_id: this.$route.query.project_id
          },
          headers: {
            token: window.sessionStorage.getItem('token')
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.is_pay = res.data.data.is_pay;
            this.user.sex = this.GET_SEX;
            this.$axios
              .get('/mobile/v1/apply/sign_up', {
                params: {
                  group_id: this.$route.query.project_id,
                  group_type: this.$route.query.projectType
                },
                headers: {
                  token: window.sessionStorage.getItem('token')
                }
              })
              .then(res => {
                if ((res.data.code = 200)) {
                  let arr = [];
                  arr = res.data.data.data.get_com.require.slice(6);
                  for (let i = 0; i < arr.length; i++) {
                    this.customize.push({
                      name: arr[i],
                      value: ''
                    });
                  }
                  console.log(this.customize);
                  // this.user = res.data.data
                }
              })
              .catch(res => {
                //  console.log(res.msg);
              });
          } else {
          }
        })
        .catch(res => {
          //  console.log(res.msg);
        });
    },
    weixinPay() {
      if (this.is_click) {
        this.is_click = false;
        this.$axios
          .get('/mobile/v1/Orderpay/wx_pay', {
            params: {
              project_id: this.$route.query.project_id
            },
            headers: {
              token: window.sessionStorage.getItem('token')
            }
          })
          .then(res => {
            if (res.data.code == 2000) {
              this.weixinPays(res.data.data);
              setTimeout(() => {
                this.is_click = true;
              }, 5000);
            } else {
              Toast(res.data.message);
            }
          })
          .catch(res => {
            //  console.log(res.msg);
          });
      } else {
        this.$toast(res.data.msg);
      }
    },
    weixinPays(data) {
      var vm = this;
      if (typeof WeixinJSBridge == 'undefined') {
        //微信浏览器内置对象。参考微信官方文档
        console.log('not wx');
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', vm.onBridgeReady(data), false);
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady(data));
          document.attachEvent('onWeixinJSBridgeReady', vm.onBridgeReady(data));
        }
      } else {
        vm.onBridgeReady(data);
      }
    },
    onBridgeReady(data) {
      var vm = this;
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          appId: data.appId, //公众号名称，由商户传入
          timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: data.nonceStr, //随机串
          package: data.package,
          signType: data.signType, //微信签名方式：
          paySign: data.paySign //微信签名
        },
        function(res) {
          // alert(JSON.stringify(res))
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            vm.$toast('支付成功');
            vm.is_pay = 1;
            vm.$router.push({
              path: '/mine/newMatch'
            });
          } else {
            vm.$toast('支付失败');
          }
        }
      );
    },
    selectSex(type) {
      let matchType = this.$route.query.projectType
			console.log(matchType.indexOf('男'))
			if(matchType.indexOf('男')!='-1'&&type==1){
				Toast('该比赛仅限男性运动员参加')
				return
			}else if(matchType.indexOf('女')!='-1'&&type==0){
				Toast('该比赛仅限女性运动员参加')
				return
			}else{
				if (type==this.user.sex) {
				} else{
					this.user.sex = type;
				}
			}
    },
    areaChange(value) {
      console.log(value);
      this.showAreaSelect = false;
      this.user.province = `${value[0].name} ${value[1].name} ${value[2].name}`;
    },
    hideAreaSelect() {
      this.showAreaSelect = false;
    },
    changePhone() {}
  }
};
</script>

<style lang="less" scoped>
/deep/ .notice{
	border-radius: 10px;
}
.confirm {
  display: flex;
  justify-content: center;
  margin-top: 0.4rem;
}
	.van-radio{
		display: inline-block;
	}
.confirmBtn {
  margin: 1rem 0;
  width: 2rem;
  background: #42b574;
  color: #fff;
  height: 0.8rem;
  line-height: 0.8rem;
  font-size: 0.32rem;
}

.pay-box {
  margin: 0.3rem;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  height: 2rem;
  width: 100%;
  align-items: flex-start;
  font-size: 0.3rem;
  font-weight: bold;
}

.pay-box-method {
  display: flex;
  height: 0.7rem;
  line-height: 0.7rem;
  width: 2rem;
  margin: 0 auto;

  .wechat {
    color: #fff;
    width: 2rem;
    background: #1ea65a;
    // 			margin-right: 0.6rem;
    // 			margin-left: 0.2rem;
  }
  .wechat_bg {
    background: #848484;
  }

  .alipay {
    color: #fff;
    width: 1.8rem;
    background: #1891e0;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
	.fade-leave-to

	/* .fade-leave-active below version 2.1.8 */
		 {
  opacity: 0;
}

.cell {
  text-align: left;

  .select-box {
    display: flex;
    justify-content: flex-end;
  }

  .iconfont {
    margin-right: 0.1rem;
    font-size: 0.34rem;
  }

  .activeSex {
    color: #42b574;
  }
}

.input {
  padding: 0;
  float: right;
  width: 2rem;
}

.short-input {
  padding: 0;
  float: right;
  width: 2.5rem;
}

.long-input {
  padding: 0;
  float: right;
  width: 3.5rem;
}
</style>
